import { createRouter, createWebHistory } from 'vue-router'
import { useTitle } from "@vueuse/core"
import { useElMessage, useElLoading } from "@usehook"
import storeInstance from "@/pinia"

export const constantRouter = [
    {
        path: '/',
        name: 'Index',
        meta: {
            title: '首页',
            onCache: true,
            onTag: false
        },
        component: () => import('@/views/Index/Index')
    },
    {
        path: '/:catchAll(.*)',
        meta: {
            onCache: false,
            onTag: false
        },
        component: { template: '<div></div>' }
    }
]

const replaceState = () => {
    history.replaceState({}, '', "/")
}

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRouter
})

const userRouter = computed(() => {
    return [...storeInstance.userStore.getRouteInfo.router.map(e => e.url), ...constantRouter.map(e => e.path)]
})

const loading = useElLoading({ manual: true, text: "页面正在加载中...", delay: 100 })

const checkRoutePermission = (routerFunc, thisRef, location, ...argArray) => {
    if (!location) return false
    if (location === router.currentRoute.value.fullPath) return false
    if (!loading.isloading.value) nextTick(() => loading.loading())
    const path = typeof location === 'string' ? location.split("?")[0] : location.path
    if (userRouter.value.includes(path)) {
        return routerFunc.call(thisRef, location, argArray)
    } else {
        useElMessage.error("该路由无权限, 请联系管理员")
        setTimeout(() => loading.close(), 10)
        return false
    }
}

const push = router.push
router.push = function (location, ...argArray) {
    return checkRoutePermission(push, this, location, ...argArray)
}

const replace = router.replace
router.replace = function (location, ...argArray) {
    return checkRoutePermission(replace, this, location, argArray)
}

router.beforeEach(async (to, _from, next) => {
    const webname = storeInstance.mainStore.getWebInfo.websiteName
    const title = to.meta.title || to.name || (localStorage.getItem("lastPageTitle") === 'undefined' ? null : localStorage.getItem("lastPageTitle")) || "页面加载中"
    useTitle(title + (webname ? ` | ${webname}` : ''))
    // 判断用户是否登录，未登录跳转到首页
    if (!storeInstance.userStore.islogin && to.path !== '/') {
        replaceState()
        return next({ path: "/" })
    } else if (storeInstance.userStore.islogin && (!storeInstance.userStore.getRouteInfo.menu || !storeInstance.userStore.getRouteInfo.menu.length)) {
        const status = await storeInstance.userStore.getUserRouteInfo()
        if (status) {
            return next({ ...to, replace: true })
        } else if (to.path !== '/') {
            replaceState()
            return next({ path: "/" })
        }
    }
    next()
})

router.beforeResolve(() => {
    loading.close()
})

export default router
